<?php


namespace app\controller;


use app\BaseController;
use think\facade\Db;


class signIn extends BaseController
{
    public function  index(){
        return view();

    }
    public function  login(){
        if(request()->isPost()){
            $data = input('post.');
            if(!captcha_check($data['verifycode'])){
                return json(['state'=>204,'message'=>'验证码错误']);
            }
            if($data['t']==1) {
                $adminDate = Db::name('admin')->where('name', $data['username'])->find();
            }else{
                $adminDate = Db::name('user')->where('name', $data['username'])->find();
            }
//            return $data['username'];
            if(!$adminDate){
                return json(['state'=>204,'message'=>'没有此用户']);
            }
            if($adminDate['password']!=md5('dytsyq'.$data['password'])){
                return json(['state'=>204,'message'=>'密码错误']);
            }
            if($adminDate['state']!==1)
            {
                return json(['state'=>204,'message'=>'账号被锁定']);
            }
//            return $this->getRealIP();
            Db::name('admin')
                ->where('name', $data['username'])
                ->update(['login_at' =>$data['login_at']]);
            if($data['t']==1){
                session('role','admin');
            }else{
                session('role','user');
            }
            session('id',$adminDate['id']);
            session('username',$data['username']);
            return json(['state'=>200,'message'=>'登录成功']);
        }
    }

    public function signOut(){
        session('username',null);
        return redirect('/signin');
    }

    //    获取本地ip
    function getRealIP(){
        $forwarded = request()->header("x-forwarded-for");
        if($forwarded){
            $ip = explode(',',$forwarded)[0];
        }else{
            $ip = request()->ip();
        }
        return $ip;
    }

}